# -*- coding: utf-8 -*-
from typing import Optional

from fastapi import APIRouter, Depends, Header, HTTPException

app05 = APIRouter()

"""Dependencies 创建，导入和声明依赖"""


async def common_parameter(q: Optional[str] = None, page: int = 1, limit: int = 100):
    return {"q": q, "page": page, "limit": limit}


@app05.get('/dependency01')
async def dependency01(commons: dict = Depends(common_parameter)):
    return commons


@app05.get('/dependency02')
def dependency01(commons: dict = Depends(common_parameter)):  # Depends() 可在同步函数中继承异步函数
    return commons


"""Classes as Dependencies 作为依赖的类"""

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]


class CommonQueryParams:
    def __init__(self, q: Optional[str] = None, page: int = 1, limit: int = 100):
        self.q = q
        self.page = page
        self.limit = limit


@app05.get("/classes_as_dependencies")
# async def classes_as_dependencies(commons: CommonQueryParams = Depends(CommonQueryParams)):
# async def classes_as_dependencies(commons: CommonQueryParams = Depends()):
async def classes_as_dependencies(commons=Depends(CommonQueryParams)):
    response = {}
    if commons.q:
        response.update({"q": commons.q})
    items = fake_items_db[commons.page: commons.page + commons.limit]
    response.update({"items": items})
    return response


"""Sub-dependencies 子依赖"""


def query(q: Optional[str] = None):
    return q


def sub_query(q: str = Depends(query), last_query: Optional[str] = None):
    if not q:
        return last_query
    return q


@app05.get('/sub_dependency')
async def sub_dependency(final_query: str = Depends(sub_query, use_cache=True)):
    """ use_cache默认为True，表示当多个依赖有一个公共的子依赖时， 每次request只会调用一次多次调用将从缓存中获取 """
    return {'sub_dependency': final_query}


"""Dependencies in path operation decorators 路径操作装饰器的多依赖"""


async def verify_token(x_token: str = Header(...)):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail='X-Token header invalid')
    return x_token


async def verify_key(x_key: str = Header(...)):
    if x_key != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail='X-Key header invalid')
    return x_key


@app05.get("/dependency_in_path_operation", dependencies=[Depends(verify_token), Depends(verify_key)])
async def dependency_path_operation():
    """dependencies 多依赖"""
    return [{"user": "user01"}, {"user": "user02"}]


"""Globel Dependencies 全局依赖"""

# # 写法
# app05 = APIRouter(dependencies=[Depends(verify_token), Depends(verify_key)])

